import React from 'react';
import PropTypes from 'prop-types';
import Add from './add'
import { stripesConnect } from '@folio/stripes/core';
import { injectIntl,FormattedMessage } from 'react-intl';
import moment from 'moment';
class AddFormSachet extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            operator: {},
            editParams:{},
            rules:{},
            selectedUserList:[]
        };
    }
    static manifest = Object.freeze({
        getQueryRulesParam: { initialValue: '' },
        httpBlackListInvoke: {
          type: 'okapi',
          accumulate: true,
          path: () => 'party/reader/credit/record/admin/commit'
        },
        httpRulesInvoke: {
          type: 'okapi',
          accumulate: true,
          path: () => 'party/rules',
          GET:{
            params: {
              query: '${getQueryRulesParam}'
            }
          }
        },
        findUserHttpInvoke: {
          type: 'okapi',
          accumulate: true,
          path: () => 'party/users',
          params: {
            query: ''
          }
        }
      });
    static propTypes = {
        mutator: PropTypes.shape({
            httpBlackListInvoke: PropTypes.shape({
            POST: PropTypes.func.isRequired,
       
          }) ,
          httpRulesInvoke: PropTypes.shape({
        
            GET: PropTypes.func.isRequired,
           
          }) ,
          findUserHttpInvoke: PropTypes.shape({
        
            GET: PropTypes.func.isRequired,
           
          }) 
        }).isRequired,
        name:PropTypes.string,
        okapi:PropTypes.object,
        params:PropTypes.object,
        removeTopMenu:PropTypes.func,
        matchPath:PropTypes.string,
        toModel:PropTypes.func
      }; 
    componentDidMount(){
        this.initData();
        const { currentUser } = this.props.okapi;
        if (currentUser) {
          this.setState({
            operator: currentUser
          });
        }
    }
    initData = () => {
      
      const { GET } = this.props.mutator.httpRulesInvoke;
       
       const year = new Date().getFullYear().toString();

       let query = `(year == ${year})`
       this.props.mutator.getQueryRulesParam.replace(query);
       GET().then(res=>{
         const {rulesGroup,totalRecords} = res
         if(totalRecords ===0){
           alert("添加黑名单,需要先设置今年的黑名单规则!")
           this.cancel(false);
           return;
         }
         let rules = rulesGroup.find(item=>{
           return item.year===year
         });
         this.setState({rules})
       })


      };
    cancel = (flag = true) => {
        const { removeTopMenu, matchPath } = this.props;
        removeTopMenu(matchPath, flag);
      };
    editCommit = ({ requestPreferences, creds, ...formData }) => {
          const rule = this.state.rules
          const selectedUserList = this.state.selectedUserList
          if( selectedUserList .length>0){
            let readerInfoGroup = []
            selectedUserList.forEach(item=>{
               readerInfoGroup.push({
                 name:item.username,
                 mobilePhone:item.personal.mobilePhone||'',
                 barcode: item.barcode,
                 email:item.personal.email
               })
            })
            let prisonTermDay =  moment(formData.prisonTerm).diff(moment(new Date()), 'days') ;
            let punishmentRecord = {
               ruleId:rule.id,
               status:"1",
               prisonTerm:formData.prisonTerm,
               foulDescription:formData.foulDescription,
               prisonTermDay:prisonTermDay===0?1:prisonTermDay+2,
               createDate: moment(new Date()).format('YYYY-MM-DD')
            }
            formData.operator = this.state.operator;
            delete formData.operator.addresses;
            delete formData.operator.preferredContactTypeId;
            delete formData.operator.servicePoints;
            delete formData.operator.curServicePoint;
            delete formData.operator.dateOfBirth;
            let params={
              rules:rule,
              readerInfoGroup,
              punishmentRecord,
              operator:formData.operator
            }
         
            const { POST } = this.props.mutator.httpBlackListInvoke;
            POST(params).then(res=>{
              alert('黑名单添加成功!')
              this.cancel(false);
              return;
            }).catch(e=>{
              console.debug(e)
              alert('黑名单添加失败!')
              this.cancel(false);
            })
          }
  
      }
      setSelectedUserData=(data,callblack)=>{
        this.setState({selectedUserList:data},()=>{
          callblack()
        })
      }
    render() {
        return (
            <Add 
            onSubmit={this.editCommit}
            initialValues={this.state.editParams}
            cancel={this.cancel}
            exitFlag={this.state.exitFlag}
            findUserHttpInvoke={this.props.mutator.findUserHttpInvoke}
            toModel={this.props.toModel}
            removeTopMenu={this.props.removeTopMenu}
            stripes={this.props.stripes}
            form={this.props.name}
            setSelectedUserData={this.setSelectedUserData}
            >
          </Add>
        );
    }
}

 
export default injectIntl(stripesConnect(AddFormSachet));
 
